package me.numark;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.numark.model.Feed;
import me.numark.model.FeedListResponse;
import me.numark.model.News;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.utils.Constants;
import me.numark.utils.Settings;
import me.numark.utils.Utils;
import me.numark.view.FeedViewHolder;
import me.numark.view.NewsViewHolder;


public class ShareListActivity extends Activity
        implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2 {

    private News mNews;

    @InjectView(R.id.back)
    View back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.list)
    PullToRefreshListView mListView;

    private ShareAdapter mAdapter;

    private NewsViewHolder mHeaderView;

    private Date yesterday, today, year;

    private int basePadding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_list);
        ButterKnife.inject(this);
        back.setOnClickListener(this);
        title.setText(R.string.all_recommends);
        try {
            mNews = new Gson()
                    .fromJson(getIntent().getStringExtra(Constants.NEWS_EXTRA), News.class);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            finish();
        }
        mAdapter = new ShareAdapter();
        mListView.setAdapter(mAdapter);
        mListView.setOnRefreshListener(this);
        View headerView = getLayoutInflater().inflate(R.layout.news_list_item, null);
        basePadding = Utils.dp2px(this, 12);
        headerView.setPadding(basePadding, basePadding, basePadding, basePadding);
        mHeaderView = new NewsViewHolder(headerView, this);
        bindHeader();
        mListView.getRefreshableView().addHeaderView(headerView);
        mListView.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
    }

    private void bindHeader() {
        Date[] dates = Utils.getMarkDate();
        yesterday = dates[0];
        today = dates[1];
        year = dates[2];
        mHeaderView.bindNewsView(mNews.title, mNews.create_timestamp * 1000, mNews.from_str,
                mNews.face_img, today, yesterday, year);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        getShareData(0);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        getShareData(mAdapter.getCount());
    }

    private class ShareAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mFeedList.size();
        }

        @Override
        public Feed getItem(int position) {
            return mFeedList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            FeedViewHolder holder;
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.feed_list_item, parent, false);
                holder = new FeedViewHolder(view, ShareListActivity.this);
                view.setTag(holder);
            } else {
                holder = (FeedViewHolder) view.getTag();
            }
            view.setPadding(basePadding, 0, basePadding, basePadding);
            holder.bindFeedView(getItem(position), today, yesterday, year, false);
            return view;
        }
    }

    private List<Feed> mFeedList = new ArrayList<Feed>();

    private void getShareData(final int start) {
        String url = String
                .format(NetworkConstants.GET_NEWS_SHARES_URL, Settings.getUid(), mNews.id);
        Map<String, String> params = new HashMap<String, String>();
        params.put("start", Integer.toString(start));
        params.put("limit", "20");
        GsonRequest<FeedListResponse> request = new GsonRequest<FeedListResponse>(url,
                Request.Method.GET, FeedListResponse.class, true, params,
                new Response.Listener<FeedListResponse>() {
                    @Override
                    public void onResponse(FeedListResponse response) {
                        mListView.onRefreshComplete();
                        if (response.ret) {
                            if (response.data != null) {
                                if (start == 0) {
                                    mFeedList.clear();
                                }
                                mFeedList.addAll(Arrays.asList(response.data));
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mListView.onRefreshComplete();
            }
        });
        NetworkHelper.getInstance().getRequestQueue().add(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }


}
